package com.eascs.tdriskcloud.controller;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import javax.inject.Inject;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLSocketFactory;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.alibaba.fastjson.JSON;
import com.eascs.tdriskcloud.entity.FraudApiResponse;
import com.eascs.tdriskcloud.form.BaseInfoForm;
import com.eascs.tdriskcloud.service.TDRiskCloudService;

public class FraudApiInvoker {

	private final Log log = LogFactory.getLog(this.getClass());
	private static final String apiUrl = "https://apitest.tongdun.cn/riskService/v1.1";

	@Inject
	static TDRiskCloudService tdDao;
	
	private HttpsURLConnection conn;

	public FraudApiResponse invoke(Map<String, Object> params) {
		try {
			URL url = new URL(apiUrl);
			// 组织请求参数
			StringBuilder postBody = new StringBuilder();
			for (Map.Entry<String, Object> entry : params.entrySet()) {
				if (entry.getValue() == null)
					continue;
				postBody.append(entry.getKey()).append("=")
						.append(URLEncoder.encode(entry.getValue().toString(), "utf-8")).append("&");
			}

			if (!params.isEmpty()) {
				postBody.deleteCharAt(postBody.length() - 1);
			}

			SSLSocketFactory ssf = (SSLSocketFactory) SSLSocketFactory.getDefault();
			conn = (HttpsURLConnection) url.openConnection();
			conn.setSSLSocketFactory(ssf);
			// 设置长链接
			conn.setRequestProperty("Connection", "Keep-Alive");
			// 设置连接超时
			conn.setConnectTimeout(1000);
			// 设置读取超时，建议设置为500ms。若同时调用了信息核验服务，请与客户经理协商确认具体时间
			conn.setReadTimeout(500);
			// 提交参数
			conn.setRequestMethod("POST");
			conn.setDoOutput(true);
			conn.getOutputStream().write(postBody.toString().getBytes());
			conn.getOutputStream().flush();
			int responseCode = conn.getResponseCode();
			if (responseCode != 200) {
				log.warn("[FraudApiInvoker] invoke failed, response status:" + responseCode);
				return null;
			}
			BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
			StringBuilder result = new StringBuilder();
			String line;
			while ((line = bufferedReader.readLine()) != null) {
				result.append(line).append("\n");
			}
			return JSON.parseObject(result.toString().trim(), FraudApiResponse.class);
		} catch (Exception e) {
			log.error("[FraudApiInvoker] invoke throw exception, details: " + e);
		}
		return null;
	}

	public static void main(String[] args) {
		 Map<String, Object> params = new HashMap<String, Object>();
	        params.put("partner_code", "YYTgroup");// 此处值填写您的合作方标识
	        params.put("secret_key", "578052a0a1094412ac2882e6249b5abe");// 此处填写对应app密钥
	        params.put("event_id", "Loan_web_20170524");// 此处填写策略集上的事件标识
	        params.put("account_name","皮晴晴");
	        params.put("id_number","370404199006301915");
	        params.put("account_mobile","15961718173");
	        BaseInfoForm entity = new BaseInfoForm();
	        entity.setBillCode("ceshi");
	        entity.setAccountName("皮晴晴");
	        entity.setAccountMobile("15961718173");
	        entity.setIdNumber("370404199006301915");
	        //params.put("people", "{\"contact_name\":\"皮晴晴\",\"info\":{\"contacts_mobile\":\"15961718173\",\"id_number\":\"370404199006301915\"}}");// 此处填写系统对象
	        FraudApiResponse apiResp = new FraudApiInvoker().invoke(params);
	        System.out.println(apiResp.getSuccess());
	        System.out.println(apiResp.getReason_code());
	        //tdDao.saveOutPutApiInfo(apiResp, entity);
	}

	public static void heartbeat() {
		final FraudApiInvoker invoker = new FraudApiInvoker();
		final Map<String, Object> params = new HashMap<>();
		params.put("partner_code", "YYTgroup");
		params.put("secret_key", "heartbeat");
		new Thread(new Runnable() {
			@Override
			public void run() {
				while (true) {
					try {
						invoker.invoke(params);
						Thread.sleep(60000);
					} catch (InterruptedException e) {
						break;
					}
				}
			}
		}, "FraudApiInvoker Heartbeat Thread").start();
	}
}
